﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Model.Other;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace Service
{
    public class TokenUtil : ITokenUtil
    {
        private readonly JWTTokenOptions _JWTTokenOptions;
        public readonly IConfiguration _configuration;

        public TokenUtil(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions, IConfiguration configuration)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
            _configuration = configuration;
        }

        public string getToken(string userId)
        {
            string exp = $"{new DateTimeOffset(DateTime.Now.AddDays(30)).ToUnixTimeSeconds()}";
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userId),
                new Claim (JwtRegisteredClaimNames.Exp, exp) //过期时间
            };
            //Signature
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
            //生成Token
            var Token = new JwtSecurityToken(
                    issuer: _configuration["Authentication:Issuer"],        //发布者
                    audience: _configuration["Authentication:Audience"],    //接收者
                    claims: claims,                                         //存放的用户信息
                    notBefore: DateTime.UtcNow,                             //发布时间
                    expires: DateTime.UtcNow.AddDays(30),                      //有效期设置为30天
                    signingCredentials                                      //数字签名
                );
            //生成字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);

            return "bearer " + TokenStr;
        }

        //判断是否过时
        public  bool IsExp(string jwtStr)
        {
            return this.GetExp(jwtStr) < DateTime.Now;
        }

        //获取过期时间
        public  DateTime GetExp(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken securityToken = jwtHandler.ReadJwtToken(jwtStr);
            int time = this.GetInt(securityToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0);
            DateTime expDate = this.GetTimeSpmpToDate(time);
            return expDate;
        }

        //object转int
        public  int GetInt(object obj)
        {
            if (obj == null)
                return 0;
            int _number = 0;
            bool reslut = Int32.TryParse(obj.ToString(), out _number);
            return _number;

        }
        // 时间戳转换成日期
        private  DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
        private  long longTime = 621355968000000000;
        private  int samllTime = 10000000;
        public  DateTime GetTimeSpmpToDate(object timeStamp)
        {
            if (timeStamp == null) return dateStart;
            DateTime dateTime = new DateTime(longTime + Convert.ToInt64(timeStamp) * samllTime, DateTimeKind.Utc).ToLocalTime();
            return dateTime;
        }
    }
}
